package com.y.demo.controller;

import com.y.demo.entity.LoginData;
import com.y.demo.entity.LoginUser;
import com.y.demo.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Controller
@ResponseBody
public class LoginUserController {
    SimpleDateFormat ft=new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
    @Autowired(required=false)
    private LoginMapper loginMapper;
    @RequestMapping("/1")
    public int all(HttpServletRequest httpServletRequest){
        LoginUser loginUser = (LoginUser) httpServletRequest.getSession().getAttribute("user");
        if (loginUser == null){
            return 0;
        }else {
            return 1;
        }
    }
    @RequestMapping("/login")
    public int findAll(HttpServletRequest httpServletRequest, @RequestBody LoginData loginData){
        httpServletRequest.getSession().setAttribute("user",1);
        List<LoginUser> loginUsers = loginMapper.selectAll();
        int flag = 0;
        for (LoginUser x:loginUsers){
            if (Objects.equals(x.getUsername(), loginData.getName()) && Objects.equals(x.getPassword(), loginData.getPassword())) {
                httpServletRequest.getSession().setAttribute("user",x);
                flag = 1;
            }else {
                flag = 2;
            }
        }
        //判断是否登录成功
        if (flag == 0){
            return 0;
        }else {
            if (flag == 1){
                return 1;
            }else {
                return 2;
            }
        }
    }
    @RequestMapping("/register")
    public boolean registerUser(HttpServletRequest httpServletRequest, @RequestBody LoginData loginData){
        String ip = httpServletRequest.getRemoteAddr();
        LoginUser loginUser1 = loginMapper.selectOneByName(loginData.getName());
        System.out.println(loginUser1);
        if (loginUser1 == null){//原本不存在此人
            //LoginData loginData1 = (LoginData) httpServletRequest.getSession().getAttribute("user");//1
            int rows = loginMapper.addUser(loginData.getName(),ip,ft.format(new Date()),ft.format(new Date()),loginData.getPassword(),"0");
            if (rows > 0){
                LoginUser loginUser = loginMapper.selectOneByName(loginData.getName());
                httpServletRequest.getSession().setAttribute("user",loginUser);
                return true;
            }else {
                return false;
            }
        }else {//注册用户已存在
            return false;
        }
    }
}
